<?php

namespace app\controller;

use app\BaseController;
use app\model\Recyclables as RecyclablesModel;
use app\Model\User as UserModel;
use app\Request;
use app\validate\User as UserValidate;
use think\db\Where;
use think\exception\ValidateException;
use app\Model\Favorite as FavoriteModel;
use app\model\History as HistoryModel;
use think\response\Json;

class User extends BaseController
{
    /*
     * 注册
     * */
    public function registration()
    {
        //获取注册信息
        $userInfo = $this->request->param();
        //判断是否有传注册信息
        if (empty($userInfo['tel']) || empty($userInfo['password'])) {
            return json(['code' => 555, 'msg' => '参数错误']);
        }
        //验证注册信息
        try {
            validate(UserValidate::class)->check([
                'tel' => $userInfo['tel'],
                'password' => $userInfo['password'],
            ]);
        } catch (ValidateException $e) {
            // 验证失败
            return json(['code' => 546, 'msg' => $e->getError()]);
        }

        $tel = $userInfo['tel'];
        $password = md5(md5($userInfo['password']));

        //判断当前手机号是否已经注册
        $result = UserModel::where('tel', $tel)->find();
        //已经注册
        if ($result != null) {
            return json(['code' => 547, 'msg' => '手机号已注册']);
        }
        //未注册，生成token和用户名
        $token = bin2hex(random_bytes(32));
        $nick = '用户_' . substr($tel, -4);;
        //注册信息写入数据库
        $insertResult = UserModel::create([
            'password' => $password,
            'tel' => $tel,
            'token' => $token,
            'nick' => $nick,
        ]);

        if ($insertResult->id) {//注册成功
            return json(['code' => 200, 'msg' => '注册成功']);
        } else {//注册信息写入数据库失败
            return json(['code' => 557, 'msg' => '注册失败']);
        }
    }

    /*
     * 获取验证码
     * */
    public function getCaptcha()
    {
        $captcha = mt_rand(1000, 9999);
        return json(['code' => 200, 'captcha' => $captcha]);
    }

    /*
     * 登录
     * */
    public function login()
    {
        $userInfo = $this->request->param();
        if (empty($userInfo['tel']) || empty($userInfo['password'])) {
            return json(['code' => 555, 'msg' => '参数错误']);
        }
        //验证登录信息格式
        try {
            validate(UserValidate::class)->check([
                'tel' => $userInfo['tel']
            ]);
        } catch (ValidateException $e) {
            // 验证失败
            return json(['code' => 546, 'msg' => $e->getError()]);
        }

        $tel = $userInfo['tel'];
        $password = md5(md5($userInfo['password']));

        //查询用户是否存在
        $user = UserModel::where('tel', $tel)->field('token,password')->find();
        if (empty($user)) {
            return json(['code' => 549, 'msg' => '用户不存在']);
        }
        //判断密码是否正确
        if ($password != $user->password) {
            return json(['code' => 550, 'msg' => '密码错误']);
        }
        //密码，生成token，更新token
        $token = bin2hex(random_bytes(32));
        $user->token = $token;
        $user->save();
        //返回用户token
        return json(['code' => 200, 'msg' => '登录成功', 'token' => $user->token]);
    }

    /*
     * 获取用户信息*/
    public function getUserInfo(Request $request)
    {
        //获取用户id
        $userId = $request->userId;
        //用户id查询用户信息
        $userInfo = UserModel::field('id,nick,avatar,tel')->find($userId);
        if (empty($userInfo)) {
            //用户不存在
            return json(['code' => 556, 'msg' => '用户不存在']);
        }
        return json(['code' => 200, 'userInfo' => $userInfo]);

    }

    /*
     * 获取我的收藏
     * */
    public function getMyFavorite(Request $request)
    {
        //获取用户id
        $userId = $request->userId;
        $pageSize = $this->request->param('pageSize', 15); // 默认每页15条
        $currentPage = $this->request->param('currentPage', 1);// 默认第1页

        //关联模型查询并分页
        $myFavorite = FavoriteModel::with([
            'recyclables' => function ($query) {
                // 限定 recyclables 的字段
                $query->field(['id,user_id,title,price,image,want_buy'])->with(['user' => function ($query) {
                    // 限定 recyclables 的字段
                    $query->field(['id,nick,avatar']);
                }]);
            }
        ])
            ->where(['user_id' => $userId])//用户的id查询收藏的回收物
            ->where(['favorite_statu'=>1])
            ->order(['favorite_time' => 'desc'])
            ->paginate([//分页查询
                'page' => $currentPage,
                'list_rows' => $pageSize,
            ]);
        if ($myFavorite->total() == 0) {
            return json(['code' => 560, 'msg' => '这里啥也没有']);
        }
        return json(['code' => 200, 'myFavorite' => $myFavorite]);


    }

    /*
     * 删除我的收藏
     * */
    public function delMyFavorite(Request $request)
    {
        //获取用户id
        $userId = $request->userId;
        $id = $this->request->param('id');

        if (empty($id)) {
            return json(['code' => 555, 'msg' => '参数错误']);
        }

        $myFavorite = FavoriteModel::where(['user_id' => $userId, 'id' => $id])->find();
        if (empty($myFavorite)) {
            return json(['code' => 558, 'msg' => '您未收藏此回收物']);
        }
        $myFavorite->favorite_statu = 0;
        $result = $myFavorite->save();

        if (!$result) {
            //数据库修改失败
            return json(['code' => 557, 'msg' => '删除失败']);
        }
        return json(['code' => 200, 'msg' => '删除成功']);

    }

    /*
     * 获取历史浏览足迹
     * */
    public function getHistoryBrowsing(Request $request){
        //获取用户id
        $userId = $request->userId;
        $pageSize = $this->request->param('pageSize', 15); // 默认每页15条
        $currentPage = $this->request->param('currentPage', 1);// 默认第1页

        //关联Recyclables模型，进行分页查询
        $historyBrowsing = HistoryModel::with(['browsingRecyclables' => function ($query) {
            $query->field(['id,image,price']);
        }])
            ->where(['user_id' => $userId])//用户的id查询浏览的回收物
            ->where(['history_statu'=>1])//历史浏览的足迹状态
                ->order(['browsing_time' => 'desc'])
            ->paginate([//分页查询
                'page' => $currentPage,
                'list_rows' => $pageSize,
            ]);
        //没有历史浏览足迹
        if ($historyBrowsing->total() == 0) {
            return json(['code' => 560, 'msg' => '空空如也']);
        }

        return json(['code' => 200, 'historyBrowsing' => $historyBrowsing]);
    }

    /*
     * 增加历史浏览
     * */
    public function addHistoryBrowsing(Request $request){
        //获取回收物id
        $recyclablesId = $this->request->param('id');
        //获取用户id
        $userId = $request->userId;
        //查询用户是否浏览过此回收物
        $findResult = HistoryModel::where(['user_id'=>$userId])
            ->where(['recyclables_id'=>$recyclablesId])
            ->find();

        $result = null;
        if (empty($findResult)) {//没有浏览过，添加到历史浏览里面
            $result = HistoryModel::create([
                'user_id' => $userId,
                'recyclables_id' => $recyclablesId,
            ]);
        }else{//有浏览过，更新浏览时间
            $result = HistoryModel::update([
                'browsing_time' => time(),
            ],['recyclables_id'=>$recyclablesId,'user_id'=>$userId]);
        }

        return json(['code' => 200, 'result' => $result]);

    }

    /*
     * 删除历史浏览
     * */
    public function delHistoryBrowsing(Request $request){
        $userId = $request->userId;
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 555, 'msg' => '参数错误']);
        }

        $reslut = HistoryModel::where(['user_id'=>$userId,'id'=>$id])->delete();
        if (!$reslut) {
            return json(['code' => 558, 'msg' => '删除失败']);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }

}